package com.hk.admin.spring.config;

import com.hk.admin.spring.interceptor.MenuAuthInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.io.File;

/**
 * <br>
 * <b>功能：</b>MVC配置<br>
 * 例如：public/image/** -> 磁盘某个位置<br>
 * 例如：拦截器<br>
 * <b>作者：</b>Pan.ShiJu<br>
 * <b>日期：</b>2017/4/11 23:27<br>
 */
@Configuration
@EnableConfigurationProperties(FileUploadConfig.class)
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    private static final String FILE_START = "file:";

    @Autowired
    private FileUploadConfig fileUploadConfig;
    @Autowired
    private MenuAuthInterceptor menuAuthInterceptor;

    /**
     * 静态资源映射
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 要以文件分隔符结尾
        String location = FILE_START + fileUploadConfig.getRootPath();
        if (!location.endsWith(File.separator)) {
            location = location + File.separator;
        }
        registry.addResourceHandler(fileUploadConfig.getResourceHandler()).addResourceLocations(location);
        super.addResourceHandlers(registry);
    }

    /**
     * 拦截器配置
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 多个拦截器组成一个拦截器链
        // addPathPatterns 用于添加拦截规则
        // excludePathPatterns 用户排除拦截
        registry.addInterceptor(menuAuthInterceptor).addPathPatterns("/**");
        super.addInterceptors(registry);
    }

}
